import {Component, OnInit} from '@angular/core';
import {GroupService} from '../group.service';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {ActivatedRoute, Router} from "@angular/router";
import {AliyunOssOutputUrl} from '../../../../config/api';
import * as moment from 'moment';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";


@Component({
  selector: 'app-group-list',
  templateUrl: './grouplist.component.html',
  styleUrls: ['./grouplist.component.scss'],

})

export class GrouplistComponent implements OnInit {

  isCollapsed = false;
  typeOpen = true;
  sliderWidth = 180;
  total = 0;
  loading = true;
  pageSize = 10;
  page = 1;
  name = '';
  status = '';
  order = {
    "start_date": "desc",
    'created_at': "desc"
  };
  orderJson = {
    "start_date": 'descend'
  };
  stage = 1;  // 1-	未开始  2-进行中  3-已结束 4-已暂停
  group_type = 0;  // 1 - 普通 2 - 拉新 3 - 抽奖
  groupsList = [];
  checkedIds = [];
  _allChecked = false;
  _indeterminate = false;
  isVisibleMiddle = false;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  qrcodeForm: FormGroup;
  start_date = null;
  end_date = null;
  _checked = false;
  qodeFormStatus = false;
  isLoadingAdd = false;
  qrcodeList = [];
  activityId = null;
  activity_goods_id = null;

  qrcodePageSize = 3;
  qrcodePage = 1;
  qrcodeTotal = 0;
  qrcodePageList = [];
  startIndex = 0;
  endIndex = 0;
  codeLoading = false;
  flag = true;
  dataURL = '';


  addQodeForm() {
    if (this.qodeFormStatus) {
      return;
    }
    this.qodeFormStatus = true;
  }

  keyDown(e) {
    e.code === 'Enter' ? this.getList(true) : '';
  }

  cancelAddCode() {
    if (this.isLoadingAdd) {
      this._message.create('warning', '正在添加中,请勿取消');
      return;
    }
    this.qodeFormStatus = false;
  }

  openType(item, type) { // 打开拼团详情
    item[type] = !item[type];
    const activityId = item.id;
    const activityGoodsId = item.activity_goods[0].id;
    if (item[type] && type == 'showProduct') {
      let flag = true;
      let index = 0;
      this.groupsList.forEach((e, i) => {
        if (e.id == item.id) {
          index = i;
          if (e.goodsInfo) {
            flag = false;
          }
        }
      });
      if (flag) {
        this.groupService.getGoodsDetail(activityId, activityGoodsId).subscribe(res => {
          if (res.data.goods_num) {
            res.data.goods_numList = res.data.goods_num.split('|');
          }
          if (res.data.prize_info) {
            res.data.prize_info.forEach(item3 => {
              if (item3.prize_num) {
                item3.prize_num = item3.prize_num.split("|");
              }
            })
            this.groupsList[index].goodsInfo = res.data;
          } else {
            this.groupsList[index].goodsInfo = res.data;
            this.groupsList[index].goodsInfo.prize_info = [];
          }
        })
      }
    }
    ;
    if (item[type] && type == 'showGroup') {
      let flag = true;
      let index = 0;
      this.groupsList.forEach((e, i) => {
        if (e.id === item.id) {
          index = i;
          if (e.groupInfo) {
            flag = false;
          }
        }
      });
      if (flag) {
        this.groupService.getGroupDetail(activityId, activityGoodsId).subscribe(res => {
          this.groupsList[index].groupInfo = res.data;
        })
      }
    }
  }

  _checkAll(value) {
    if (value) {
      this.groupsList.forEach(item => {
        if (!item.checked) {
          item.checked = true;
          this.checkedIds.push(item.id);
        }
      });
    } else {
      this.groupsList.forEach(item => {
        if (item.checked) {
          item.checked = false;
          this.checkedIds.every((val, idx, array) => {
            if (item.id === val) {
              this.checkedIds.splice(idx, 1);
              return false;
            }
            return true;
          });
        }
      });
    }
    this._refreshStatus();
  };

  checkedSingele(e, id) {
    if (e) {
      this.checkedIds.push(id);
    } else {
      this.checkedIds.every((val, idx, array) => {
        if (id === val) {
          this.checkedIds.splice(idx, 1);
          return false;
        }
        return true;
      });
      this.groupsList.every((val, idx, array) => {
        if (id === val.id) {
          val.checked = false;
          return false;
        }
        return true;
      })
    }
    this._refreshStatus();
  }

  _refreshStatus() {
    const allChecked = this.groupsList.every(value => value.checked === true);
    const allUnChecked = this.groupsList.every(value => !value.checked);
    console.log(allChecked, allUnChecked);
    this._allChecked = allChecked;
    this._indeterminate = (!allChecked) && (!allUnChecked);
  };

  goAddPage(i) {
    if (this.flag) {
      this.router.navigate([i != 3 ? 'member/group/add/' + i : 'member/group/add-lottery/' + i], {
        queryParams: {
          type: this.group_type + 1,
          stage: this.stage
        }
      });
      this.flag = false;
    }
  }

  goEditPage(id) {
    if (this.flag) {
      this.router.navigate([this.group_type === 2 ? 'member/group/edit-lottery/' + id : 'member/group/edit/' + id],
        {
          queryParams: {
            'type': this.group_type + 1,
            'stage': this.stage
          }
        });
      this.flag = false;
    }
  }

  goWinnerPage(id) {
    if (this.flag) {
      this.router.navigate(['member/group/winners-detail/' + id], {
        queryParams: {
          'type': this.group_type + 1,
          'stage': this.stage
        }
      });
      this.flag = false;
    }
  }


  goResetPage(id) {
    if (this.flag) {
      this.router.navigate([this.group_type === 2 ? 'member/group/add-lottery/' + id : `member/group/add/${this.group_type + 1}/${id}`],
        {
          queryParams: {
            'type': this.group_type + 1,
            'stage': this.stage
          }
        })
    }
  }

  saveStatus() {
    if (this.stage == 2) {
      window.localStorage.setItem('status', '1');
    } else if (this.stage == 4) {
      window.localStorage.setItem('status', '2');
    } else {
      window.localStorage.setItem('status', '');
    }
  }


  toggleCollapsed(value) {
    this.isCollapsed = value;
    if (!this.isCollapsed) {
      this.typeOpen = true;
    }
  }

  showShadow(i, flag) {
    console.log(flag);
    if (!flag) {
      this.qrcodePageList[i]['shadow'] = true;
    }
  }

  hideShadow(i, flag) {
    if (!flag) {
      this.qrcodePageList[i]['shadow'] = false;
    }
  }

  toggleShow(qrcode) {
    let status = qrcode.status === '正常' ? '暂停' : '正常';
    this.groupService.postActivityStatus(qrcode.id, status).subscribe(res => {
      if (res.code === 2000) {
        this._message.create('success', `修改成功`);
        this.getQrCodeList();
      } else {
        this._message.create('error', res.message);
      }
    });
  }

  constructor(private groupService: GroupService,
              private _message: NzMessageService,
              private confirmServ: NzModalService,
              private activatedRoute: ActivatedRoute,
              private router: Router,
              private fb: FormBuilder,
  ) {

    const self = this;
    if (Object.keys(this.activatedRoute.queryParams['_value']).length) {
      this.activatedRoute.queryParams.subscribe(queryParams => {
        self.group_type = parseInt(queryParams.type) - 1;
        self.changeGroupStage(parseInt(queryParams.stage));
      });
    } else {
      this.group_type = 0;
      this.changeGroupStage(1);
    }
    this.qrcodeForm = this.fb.group({
      start_date: [null, [Validators.required]],
      end_date: [null, [Validators.required]],
      head_free_price: [0, [Validators.required]],
      id: [null, [Validators.required]],
      activity_goods_id: [null, [Validators.required]],
      is_give: [false],
      is_show: [false]
    })
  }

  getFormControl(name) {
    return this.qrcodeForm.controls[name];
  }

  ngOnInit() {
    this.groupsList = [{
      id: 1,
      name: '巧妈妈澳大利亚精品500克果冻转发朋友圈朋友圈友圈',
      state: 1,
      price: 10000,
      start: '2017.01.31',
      end: '2017.12.25',
      showGroup: true,
      showProduct: true
    }];
    this.loading = false;
    this.qrcodeForm.controls['start_date'].setValue(new Date(moment(new Date().getTime()).format('YYYY-MM-DD') + ' 00:00:00'));
    this.qrcodeForm.controls['end_date'].setValue(new Date(moment(new Date().getTime()).format('YYYY-MM-DD') + ' 23:59:59'));
  }


  getList(clearPage?, side?) { // 拉新 和 普通
    if (clearPage) {
      this.page = 1;
      this.order = {
        "start_date": "desc",
        'created_at': "desc"
      };
      this.orderJson = {
        "start_date": 'descend'
      };
    }
    this.loading = true;
    this._allChecked = false;
    this.checkedIds = [];
    if (side) {
      this.router.navigate(['member/group/list'], {
        queryParams: {
          type: this.group_type + 1,
          stage: this.stage,
        }
      });
      this.order = {
        "start_date": "desc",
        'created_at': "desc"
      };
      this.orderJson = {
        "start_date": 'descend'
      };
      if (this.stage == 2) {
        this.status = '1';
      } else if (this.stage == 4) {
        this.status = '2';
      } else {
        this.status = '';
      }

    }
    this.groupService.getActivityList(this.page, this.pageSize, this.stage, this.group_type + 1, this.name, JSON.stringify(this.order), this.status).subscribe(res => {
      if (res.code === 2000) {
        this.total = res.data.total;
        this.groupsList = res.data.data;
        this.groupsList.map((e, i) => {
          e.activity_goods[0].price = e.activity_goods[0].price / 1000;
          let date = new Date(e['end_date'] + ' 23:59:59').getTime();
          let date1 = new Date().getTime();
          e['effective'] = true;
          if (date < date1) {
            e['effective'] = false;
          }
        })
        this._indeterminate = false;
      } else {
        this.groupsList = [];
      }
      this.loading = false;
    });
  }

  sort(type, value) {
    if (value) {
      this.order[type] = value.substring(0, value.length - 3);
      this.order['created_at'] = value.substring(0, value.length - 3);
      this.orderJson[type] = value;
    } else {
      this.orderJson[type] = 'descend';
      this.order[type] = 'desc';
      this.order['created_at'] = 'desc';
    }
    this.page = 1;
    this.getList();
  }

  changeGroupStage(stage) {
    this.stage = stage;
    this.name = '';
    this._allChecked = false;
    this.checkedIds = [];
    this.order = {
      "start_date": "desc",
      'created_at': "desc"
    };
    this.orderJson = {
      "start_date": 'descend'
    };

    this.getList(true, true);
  }

  deleteGroup(id) {
    const self = this;
    this.confirmServ.confirm({
      title: `删除拼团`,
      content: '您确定要删除此拼团吗？',
      onOk() {
        self.groupService.delActivity(id).subscribe(res => {
          if (res.code === 2000) {
            let _lastCheckedIds = self.checkedIds;
            self._message.create('success', `拼团删除成功`);
            self.page = 1;
            self.getList();
            setTimeout(() => {
              self.checkedIds = [];
              _lastCheckedIds.forEach((e, i) => {
                self.checkedSingele(true, e);
                self.groupsList.forEach((e1, i1) => {
                  if (e1.id === e) {
                    e1.checked = true;
                  }
                });
              });
              self.checkedSingele(false, id);
              if (self.groupsList.length === 0) {
                self._indeterminate = false;
                self._allChecked = false;
              }
            }, 300)
          } else {
            self._message.create('error', res.message);
          }
        });
      },
      onCancel() {
      }
    });
  }

  // 修改拼团状态
  changeGroupStatus(id, status) {
    let title, content;
    if (status === '正常') {
      title = '恢复拼团';
      content = '您确定要恢复此拼团吗？';
    } else {
      title = '暂停拼团';
      content = '您确定要暂停此拼团吗？';
    }
    const self = this;
    this.confirmServ.confirm({
      title: title,
      content: content,
      onOk() {
        self.groupService.postActivityStatus(id, status).subscribe(res => {
          if (res.code === 2000) {
            self._message.create('success', `拼团状态修改成功`);
            let _lastCheckedIds = self.checkedIds;
            self.page = 1;
            self.getList();
            setTimeout(() => {
              self.checkedIds = [];
              _lastCheckedIds.forEach((e, i) => {
                self.checkedSingele(true, e);
                self.groupsList.forEach((e1, i1) => {
                  if (e1.id === e) {
                    e1.checked = true;
                  }
                })
              });
              self.checkedSingele(false, id);
            }, 300)
          } else {
            self._message.create('error', res.message);
          }
        });
      },
      onCancel() {
      }
    });
  }

  deleteCheckedGroup() {
    const self = this;
    if (this.checkedIds.length > 0) {
      this.confirmServ.confirm({
        title: `批量删除拼团`,
        content: '您确定要批量删除拼团吗？',
        onOk() {
          let num = 0;
          self.checkedIds.map((e, i) => {
            self.groupService.delActivity(e).subscribe(res => {
              if (res.code === 2000) {
                num++;
                if (num === self.checkedIds.length) {
                  self._message.create('success', `拼团批量删除成功`);
                  self.page = 1;
                  self.getList();
                }
              } else {
                self._message.create('error', res.message);
              }
            })
          })
        },
        onCancel() {
        }
      });
    }
  }

  batchCheckedGroupStatus(status) {
    const self = this;
    if (this.checkedIds.length > 0) {
      this.confirmServ.confirm({
        title: `批量${status}拼团`,
        content: `您确定要批量${status}拼团吗？`,
        onOk() {
          let num = 0;
          self.checkedIds.map((e, i) => {
            self.groupService.postActivityStatus(e, status).subscribe(res => {
              if (res.code === 2000) {
                num++;
                let _lastCheckedIds = self.checkedIds;
                if (num === self.checkedIds.length) {
                  status = status === '正常' ? status = '恢复' : status;
                  self._message.create('success', `拼团状态${status}成功`);
                  self.page = 1;
                  self.getList();
                  setTimeout(() => {
                    self.checkedIds = [];
                    _lastCheckedIds.forEach((e, i) => {
                      self.checkedSingele(true, e);
                      self.groupsList.forEach((e1, i1) => {
                        if (e1.id === e) {
                          e1.checked = true;
                        }
                      })
                      _lastCheckedIds.forEach((e, i) => {
                        self.checkedSingele(false, e);
                      })
                    });
                  }, 500);
                }

              } else {
                self._message.create('error', res.message);
              }
            });
          })

        },
        onCancel() {
        }
      });
    }
  }

  showQrCodeModal(item) {
    this.activityId = item.id;
    this.activity_goods_id = item.activity_goods['0'].id;
    this.isVisibleMiddle = true;
    this.qrcodeForm.controls['id'].setValue(this.activityId);
    this.qrcodeForm.controls['activity_goods_id'].setValue(this.activity_goods_id);
    this.qrcodePage = 1;
    // this.groupService.getQrcodeList(this.activityId).subscribe(res => {
    //   res.data.data.forEach((e,i) => {
    //     console.log(e['activity_goods']['0']['qr_code_url']);
    //     if(e['activity_goods']['0']['qr_code_url']) {
    //       this.qrcodeTotal+=1;
    //     }
    //   })
    // });
    this.getQrCodeList();
  }

  handleCancelMiddle(e) {
    this.isVisibleMiddle = false;
  }

  handleOkMiddle(e) {
    this.isVisibleMiddle = false;
  }

  newArray = (len) => {
    const result = [];
    for (let i = 0; i < len; i++) {
      result.push(i);
    }
    return result;
  }
  _startValueChange = () => {
    if (this.start_date > this.end_date) {
      this.end_date = null;
    }
  }
  _endValueChange = () => {
    if (this.start_date > this.end_date) {
      this.start_date = null;
    }
  }
  _disabledStartDate = (startValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!startValue || !this.qrcodeForm.value.validity_end) {
      return startValue < now_time;
    }
    return (startValue.getTime() >= this.qrcodeForm.value.validity_end.getTime()) || (startValue.getTime() <= Date.now());
  }
  _disabledEndDate = (endValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!endValue || !this.start_date) {
      return endValue.getTime() < now_time;
    }
    return endValue.getTime() < this.start_date.getTime();
  }

  get _isSameDay() {
    return this.start_date && this.end_date && moment(this.start_date).isSame(this.end_date, 'day');
  }

  get _endTime() {
    return {
      nzHideDisabledOptions: true,
      nzDisabledHours: () => {
        return this._isSameDay ? this.newArray(this.start_date.getHours()) : [];
      },
      nzDisabledMinutes: (h) => {
        if (this._isSameDay && h === this.start_date.getHours()) {
          return this.newArray(this.start_date.getMinutes());
        }
        return [];
      },
      nzDisabledSeconds: (h, m) => {
        if (this._isSameDay && h === this.start_date.getHours() && m === this.start_date.getMinutes()) {
          return this.newArray(this.start_date.getSeconds());
        }
        return [];
      }
    };
  }

  getQrCodeList(e?) {
    this.codeLoading = true;
    if (e) {
      this.qrcodePage = e;
    }

    this.startIndex = (this.qrcodePage - 1) * this.qrcodePageSize - (this.qrcodePage != 1 ? 1 : 0);
    this.endIndex = this.qrcodePage * this.qrcodePageSize - (this.qrcodePage != 1 ? 1 : 0);
    // this.startIndex = (this.qrcodePage - 1) * this.qrcodePageSize;
    // this.endIndex = this.qrcodePage * this.qrcodePageSize - 1;
    //分页切换
    // if(this.qrcodePage == 1) {
    //   this.qrcodePageSize = 2;
    // } else {
    //   this.qrcodePageSize = 3;
    // }
    // this.startIndex = (this.qrcodePage - 1) * this.qrcodePageSize + (this.qrcodePage === 1 ? 0 : -1);
    // this.endIndex = this.qrcodePage === 1 ? this.startIndex + 1 : this.startIndex + 2;

    this.groupService.getQrcodeList(this.activityId).subscribe(res => {
      this.codeLoading = false;
      this.qrcodeList = res.data.data;
      if (res.data.total != 0 && res.data.total % 3 == 0) {
        this.qrcodeTotal = res.data.total + 1;
      } else {
        this.qrcodeTotal = res.data.total;
      }
      this.qrcodePageList = [];

      this.qrcodeList.forEach((e, i) => {

        let nowTime = new Date().getTime();
        if (i >= this.startIndex && i <= this.endIndex) {
          if (nowTime > new Date(e['end_date']).getTime() + 86400000) {
            e['invalid'] = true;
          } else {
            e['invalid'] = false;
          }
          this.qrcodePageList.push(e)
        }
      });
      // if(this.qrcodePageList.length) {
      //   let nowTime = new Date().getTime();
      //   this.qrcodePageList.map((e,i) => {
      //     if(nowTime > new Date(e['end_date']).getTime() + 86400000) {
      //       e['invalid'] = true;
      //     } else {
      //       e['invalid'] = false;
      //     }
      //   });
      // }
    });
    // this.qrcodeTotal =  this.qrcodeTotal + (this.qrcodeTotal === this.endIndex + 1 ? 1 : 0);
    // console.log(this.qrcodeTotal);
    // this.endIndex = this.endIndex + (this.qrcodeTotal == this.endIndex - 1 ? 1: 0);
    // this.qrcodePageList = this.qrcodeList.slice(this.startIndex,this.endIndex);
    // console.log(this.qrcodePageList);
    // })


    //每页有新增
    // this.startIndex = (this.qrcodePage - 1) * this.qrcodePageSize;
    // this.endIndex = this.qrcodePage * this.qrcodePageSize;
    // this.groupService.getQrcodeList(this.activityId,this.qrcodePage,this.qrcodePageSize).subscribe(res => {
    //   this.qrcodeList = res.data.data;
    //   this.qrcodeTotal = res.data.total;
    //   this.codeLoading = false;
    //   if(this.qrcodeList.length) {
    //     let nowTime = new Date().getTime();
    //     this.qrcodeList.map((e,i) => {
    //       if(nowTime > new Date(e['end_date']).getTime() + 86400000) {
    //         e['invalid'] = true;
    //       } else {
    //         e['invalid'] = false;
    //       }
    //     });
    //   }
    // });
  }

  getBase64(url) {
    return new Promise((resolve, reject) => {
      var Img = new Image(),
        dataURL = '';
      Img.setAttribute('crossOrigin', 'anonymous');
      Img.src = url + '?' + new Date().getTime();
      let self = this;
      Img.onload = function () { //要先确保图片完整获取到，这是个异步事件
        var canvas = document.createElement("canvas"), //创建canvas元素
          width = Img.width, //确保canvas的尺寸和图片一样
          height = Img.height;
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").drawImage(Img, 0, 0, width, height); //将图片绘制到canvas中
        dataURL = canvas.toDataURL('image/jpeg'); //转换图片为dataURL
        self.dataURL = dataURL;
        resolve(dataURL);
      };
    });
  }


  downloadQrcode(src) {
    this.getBase64(src).then(url => {
      let url1 = url;
      let a = document.createElement('a');
      let event = new MouseEvent('click');
      a.href = url1 + '';
      a.download = name || '二维码图片';
      a.dispatchEvent(event);
    })
  }

  _submitForm() {
    this.isLoadingAdd = true;
    this.qrcodeForm.value['is_give'] = this.qrcodeForm.value['is_give'] ? 1 : 0;
    this.qrcodeForm.value['is_show'] = this.qrcodeForm.value['is_show'] ? 1 : 0;
    this.qrcodeForm.value['start_date'] = moment(this.qrcodeForm.value.start_date).format('YYYY-MM-DD');
    this.qrcodeForm.value['end_date'] = moment(this.qrcodeForm.value.end_date).format('YYYY-MM-DD');
    const data = this.qrcodeForm.value;
    this.groupService.addQrcode(data).subscribe(res => {
      if (res.code === 2000) {
        this.qrcodePage = 1;
        this.getQrCodeList();
        this.qodeFormStatus = false;
        this.qrcodeForm.controls['start_date'].setValue(new Date(moment(new Date().getTime()).format('YYYY-MM-DD') + ' 00:00:00'));
        this.qrcodeForm.controls['end_date'].setValue(new Date(moment(new Date().getTime()).format('YYYY-MM-DD') + ' 23:59:59'));
        this.qrcodeForm.controls['is_give'].setValue(false);
        this.qrcodeForm.controls['is_show'].setValue(false);
        this._message.create('success', res.message);
      } else {
        this._message.create('error', res.message);
      }
      this.isLoadingAdd = false;
    });
    // setTimeout(() => {
    //   if(!this.qrcodeList[this.activityId]) {
    //     this.qrcodeList[this.activityId] = [];
    //   }
    //   this.qrcodeList[this.activityId].push(this.qrcodeForm.value);
    //   this.qrcodePage = 1;
    //   this.qrcodePageList[this.activityId] = this.qrcodeList[this.activityId].slice(0,2);
    //   this.isLoadingAdd = false;
    //   this.qodeFormStatus = false;
    // },2000);
  }
}
